

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ssextjs.component.Button;
import com.ssextjs.component.PagingToolbar;
import com.ssextjs.component.Panel;
import com.ssextjs.component.Toolbar;
import com.ssextjs.component.grid.Column;
import com.ssextjs.component.grid.ColumnModel;
import com.ssextjs.component.grid.GridCellRenderer;
import com.ssextjs.component.grid.GridPanel;
import com.ssextjs.data.SqlReader;
import com.ssextjs.data.Store;
import com.ssextjs.engine.ConfiguraionImpl;
import com.ssextjs.engine.IdGenerator;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Servlet implementation class Index
 */
public class Index extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Configuration cfg;
	public static Store st;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Index() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init() {
    	ConfiguraionImpl.initCfg(this);
    	cfg = ConfiguraionImpl.getCfg();
		try {
		    Driver driver = (Driver)Class.forName("org.postgresql.Driver").newInstance();
		    DriverManager.registerDriver(driver);
		    System.err.println("Registered JDBC driver ");
		  }
		  catch (Exception e) {
			System.err.println("Can't register JDBC driver ");
		  }
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		
		
		Template temp = cfg.getTemplate("Index.tpl");
		IdGenerator idgen = new IdGenerator();
		
		Map root = new HashMap();
		root.put("idgen", idgen);
		root.put("cssurl", "http://localhost:8080/SSExtJS/css/");
		root.put("jsurl", "http://localhost:8080/SSExtJS/js/");
		root.put("imgurl", "http://localhost:8080/SSExtJS/images/");
		
		// Grid
		
		GridCellRenderer gcr_id = new GridCellRenderer() {
			 public String render(Map record, String colname, Object data, int rowIndex,int colIndex, Store st) {
				 int id_data = (Integer) data;
				 if (id_data<=21600 && id_data>21596) {
					 return String.format("<span style=\"color:red\">%d</span>",id_data);
				 }
				 return String.valueOf(id_data);
			 }
		};
		
		GridCellRenderer gcr_uname = new GridCellRenderer() {
			 public String render(Map record, String colname, Object data, int rowIndex,int colIndex, Store st) {
				 String username = (String) data;
				 if (rowIndex<=10) {
					 return String.format("<span style=\"color:green\">%s</span>",username);
				 }
				 return username;
			 }
		};
		
		Map grid_config = new HashMap();
		
		List<Column> colums = new ArrayList();
		colums.add((new Column("id","ID")).setRenderer(gcr_id));
		colums.add((new Column("user_name","Ник")).setWidth(200).setRenderer(gcr_uname));
		colums.add((new Column("firstname","Имя")).setWidth(150));
		//Store
		Map st_config = new HashMap();
		String[] reader_fields = {"id","user_name","firstname"};
		st_config.put("reader", new SqlReader(reader_fields));
		st_config.put("sql", "SELECT * FROM fans.tbl_fansinfo ORDER BY ID DESC LIMIT 40 OFFSET 0");
		//Store st = new Store(st_config);
		if (st==null) {
			st = new Store(st_config);
			Connection con = getConnect();
			if (con!=null) {
				con = st.load(con);
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				System.err.println("Not connect to DB.");
			}
		}
		
		ColumnModel cm = new ColumnModel(colums);
		grid_config.put("cm", cm);
		//System.err.println("ALL col width: "+grcolums.getAllWidth());
		//grid_config.put("title", "Example GRID");
		//grid_config.put("width", 600);
		//grid_config.put("height", 300);
		grid_config.put("stripeRows", true);
		//grid_config.put("forceFit", false);
		grid_config.put("store", st);
		//grid_config.put("idgen", idgen);
		
		Map b_cfg = new HashMap(); 
		b_cfg.put("text","My Button");
		//b_cfg.put("iconCls","MyButtonCLS");
		
		//Button but = new Button("MyBut");
		//but.setJSFunc("alert('Cool')").setText("My TEXT");
		
		Toolbar tbar = new Toolbar().addItem(new Button("Text","tabs","#","alert('click')").setQuickTip("It is tabs"))
									.addItem(new Button("Text 2","","#","alert('click 2')"))
									.addItem("-->")
									.addItem(new Button("Text 3","","#","alert('click 3')"))
									.addItem("|")
									.addItem(new Button("Text 4","","#","alert('click 4')"));
		//tbar.noHeader(false);
		tbar.addItem(new Button("","tabs","#","alert('click tabs')") );
		//grid_config.put("tbar", tbar);
		//Store END
		PagingToolbar pt = new PagingToolbar(0,30,90,st);
		//grid_config.put("tbar", tbar);
		Panel gp = new GridPanel(grid_config).setTitle("123").setStripeRows(true).setTbar(tbar).setBbar(pt).setForceFit(true); 
		System.err.println("StriperRows: "+gp.getStripeRows());
		root.put("gr", gp);
		Panel pn = new Panel();
		pn.setTitle("It is panel").setHTML("<h3>Cool</h3>").setStyle("margin: 5px;");
		root.put("pn", pn);
		//root.put("tbar", tbar);
		//root.put("pt", pt);
		// Grid END
		try {
			temp.process(root, out);
			out.flush();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		//out.println(this.getServletContext().getRealPath("/")+"/WEB-INF/ssextjs/templates/");
		out.close();
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	public Connection getConnect() {
		Connection con=null;
		try {
			con = DriverManager.getConnection("jdbc:postgresql://10.150.10.28/fc", "sa", "");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}

}

